const axios = require("axios");
const config = require("../config/config");
const { User } = require("../models/user");

class Wx {
  static async code2Session(code) {
    let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${config.miniProgram.appId}&secret=${config.miniProgram.appSecret}&js_code=${code}&grant_type=authorization_code`;
    const { data } = await axios.get(url);
    if (!Object.keys(data).includes("openid")) {
      throw new global.errs.AuthFailed(data.errcode +" : "+ data.errmsg);
    }
    let user = await User.validateWxLoin(data);
    if (!user) {
      user = {
        nickname: "没用AccessToken获取名字",
        openId: data.openid,
      };
      user = User.create(user);
    }
    return user;
  }

  static async getAccessToken() {
    let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.miniProgram.appId}&secret=${config.miniProgram.appSecret}`;
  }
}

module.exports = {
  Wx,
};
